var utils = require('/utils/index.js');
var base = require('/base_info.js');
var common = require('/utils/common.js');
// 富文本解析
var wxParse = require('/pages/wxParse-master/wxParse.js');
Page({
  data: {
    menber_type: '',
    // array: ['中国', '美国', '巴西', '日本'],
    // 到店时间
    objectArray: [
      {
        name: '06:00',
        id: '06'
      },
      {
        name: '07:00',
        id: '07'
      },
      {
        name: '08:00',
        id: '08'
      },
      {
        name: '09:00',
        id: '09'
      },
      {
        name: '10:00',
        id: '10'
      },
      {
        name: '11:00',
        id: '11'
      },
      {
        name: '12:00',
        id: '12'
      },
      {
        name: '13:00',
        id: '13'
      },
      {
        name: '14:00',
        id: '14'
      },
      {
        name: '15:00',
        id: '15'
      },
      {
        name: '16:00',
        id: '16'
      },
      {
        name: '17:00',
        id: '17'
      },
      {
        name: '18:00',
        id: '18'
      },
      {
        name: '19:00',
        id: '19'
      },
      {
        name: '20:00',
        id: '20'
      },
      {
        name: '21:00',
        id: '21'
      },
      {
        name: '22:00',
        id: '22'
      },
      {
        name: '23:00',
        id: '23'
      },
      {
        name: '24:00',
        id: '24'
      },
      {
        name: '次日1点',
        id: '25'
      },
      {
        name: '次日2点',
        id: '26'
      },
      {
        name: '次日3点',
        id: '27'
      },
      {
        name: '次日4点',
        id: '28'
      },
      {
        name: '次日5点',
        id: '29'
      },
      {
        name: '次日6点',
        id: '30'
      }
    ],
    clickSign: true,
    // 活动信息缓存
    activity_conetnt: false,
    timeShow: new Date().getHours(),
    arrIndex: 0,
    // index: 0,
    swiperList: [{
      id: 0,
      img: '/images/demoimg/d1.jpg'
    }, {
      id: 1,
      img: '/images/demoimg/d1.jpg'
    }, {
      id: 2,
      img: '/images/demoimg/d1.jpg'
    }],
    currentSwiper: 0,//当前状态
    indicatorDots: false,
    autoplay: true,
    interval: 3000,
    dotsIndex: 0,
    roomInfo: {},
    bannerImg: [],
    imgUrl: base.imgUrl,
    items: [],
    num:1,
    // 应付金额
    dis_cost: 0,
    discountPrice: 0,
    discountType: "",
    contacts: '',
    phone: '',
    page: 1,
    size: 10,
    commentList: [],
    room_id: "",
    breakfast: 1,
    breakfast_amount: 0,
    hotel_info: {},
    dd_time: '',
    dd_time_name: '',
    // 押金状态 false 未选中
    yj_sign: false,
    showModel: false,
    modelSign: '',
    remarks: '',
    inTimeDay: '',
    toDay: common.transTime().slice(0, 10),
    // 权益卡名称
    name: '',
    roomOrderList: [],
    roomPriceSum: 0
  },
  // 监听联系人输入
  contactsInput (e) {
    this.setData({
      contacts: e.detail.value
    });
  },
  // 监听备注信息改变
  remarkChange (e) {
    this.setData({
      remarks: e.detail.value
    });
  },
  // 阻止事件冒泡
  CatchTap () {
    return false;
  },
  // 监听手机号码输入
  phoneInput (e) {
    this.setData({
      phone: e.detail.value
    });
  },
  // 跳转到酒店图片
  imgShow () {
    console.log(1);
    my.navigateTo({
      url: './room-imgshow?id=' + this.data.room_id
    });
  },
  // 构建创建订单需要的参数
  postData(formId) {
    let that = this;
    var discountWayS = my.getStorageSync({
      key: 'discount', // 缓存数据的key
    }).data ? my.getStorageSync({
      key: 'discount', // 缓存数据的key
    }).data : '{}';
    var info = that.data.roomInfo;
    var data = {
      // 用户id
      user_id: my.getStorageSync({
        key: 'uid'
      }).data,
      seller_id: base.seller_id,
      // 权益卡id
      equitycard_id: JSON.parse(discountWayS).equitycard_id ? JSON.parse(discountWayS).id : "",
      // 优惠券id
      coupons_id: JSON.parse(discountWayS).equitycard_id ? "" : JSON.parse(discountWayS).id,
      // 房型id
      room_id: info.id,
      // 是否选择早餐
      is_breakfast: that.data.breakfast == 1 ? 0 : 1,
      // 单价
      price: info.price,
      // 早餐价格
      breakfast_amount: that.data.breakfast_amount,
      // 房间名称
      seller_name: that.data.hotel_info.name,
      // 到店时间
      arrival_time: my.getStorageSync({
        key: 'inTime',
      }).data,
      // 离店时间
      departure_time: my.getStorageSync({
        key: 'outTime',
      }).data,
      // 住店时长
      days: that.data.lightLong,
      // 到店时间
      dd_time: that.data.dd_time,
      // 电话
      tel: that.data.phone,
      // 用户名称
      name: that.data.contacts,
      // 房型类型
      room_type: info.name,
      // 总价(不包含优惠价格)
      total_cost: info.price * 1 * that.data.num * 1,
      // 房间数量
      num: that.data.num,
      // 支付宝返回的用户id
      buyer_id: my.getStorageSync({
        key: 'user_id'
      }).data,
      // 实际金额
      dis_cost: that.cost_js() * 1 + (that.data.breakfast_amount * 1),
      // 房型图片
      room_logo: info.logo,
      // 优惠券价格 
      yhq_cost: JSON.parse(discountWayS).equitycard_id ? "" : that.data.discountPrice,
      // 权益卡折扣
      equitycard_cost: JSON.parse(discountWayS).equitycard_id ? that.data.discountPrice : "",
      // 表单id
      from_id: formId,
      // 押金金额
      yj_cost: that.data.yj_sign ? info.yj_cost * 1 : 0,
      // 备注
      remarks: that.data.remarks,
      // 用户类型
      user_type: that.data.menber_type
    }
    this.createdOrder(data);
    // my.navigateTo({
    //   url: './../order/pay?data=' + JSON.stringify(data)
    // });
  },
  // 调取支付
  createdOrder (data) {
    console.log(data);
    let that = this;
    data.pay_method = that.data.yj_sign ? 2 : 1;
    utils.getData('AliTradeOrder', data, (res) => {
      // 成功
      let order_id = res.data.data.order_id;
      if (that.data.yj_sign) {
        // 调用预授权
        my.tradePay({
          orderStr: res.data.data.trade_no,
          success: (res) => {
            if (res.resultCode == 9000) {
              my.redirectTo({
                url: './../order/place-result?data=' + JSON.stringify(data) + '&order_id=' + order_id
              });
            } else {
              my.alert({
                content: '支付失败'
              });
            };
          },
          fail: (err) => {
            my.alert({
              content: '支付失败',
            });
          }
        });
        return false;
      };
      // 调用普通支付
      my.tradePay({
        tradeNO: res.data.data.trade_no,
        success: (res) => {
          if (res.resultCode == 9000) {
            my.redirectTo({
              url: './../order/place-result?data=' + JSON.stringify(data) + '&order_id=' + order_id
            });
          } else {
            my.alert({
              content: '支付失败'
            });
          }
        },
        fail: (err) => {
          my.alert({
            content: '支付失败',
          });
        }
      });
    }, (err) => {
      console.log(err);
    });
  },
  // 时间选择
  ddTime (e) {
    // console.log(this.data.showModel);
    this.setData({
      modelSign: e.currentTarget.dataset.id
    });
    this.showModelClick();
  },
  // 弹窗显示隐藏
  showModelClick () {
    this.setData({
      showModel: !this.data.showModel
    });
  },
  timeSelect (e) {
    console.log(e.currentTarget.dataset.id);
    this.setData({
      dd_time: e.currentTarget.dataset.id * 1,
      dd_time_name: e.currentTarget.dataset.name,
      showModel: !this.data.showModel
    });
  },
  // 金额计算
  cost_js () {
    let str = '';
    if (this.data.discountType == 'discount') {
      str = (this.data.dis_cost * 1 - this.data.discountPrice * 1).toFixed(2);
    } else if (this.data.discountType == 'equity') {
      str = (this.data.dis_cost * 1 * (this.data.discountPrice * 1 * 0.1)).toFixed(2);
    } else {
      str = (this.data.dis_cost * 1).toFixed(2);
    };
    return str;
  },
  // 轮播图当前激活状态改变
  swiperChange: function(e) {
    this.setData({
      currentSwiper: e.detail.current
    })
  },
  formSubmit: function(e) {
    // this.pay(e.detail.formId);
    this.goReserve(e.detail.formId);
  },
  // 是否选择早餐
  radioChange: function(e) {
    console.log(this.hotel_info);
    this.setData({
      breakfast: e.detail.value,
      breakfast_amount: e.detail.value == 0 ? this.data.hotel_info.breakfast_amount : 0
    });
  },
  //增加数量
  addNub () {
    let that = this;
    var num = this.data.num;
    // 如果大于剩余房间数量，则不允许增加
    if (that.data.roomInfo.total_num <= num) {
      return false;
    };
    // 不作过多考虑自增1
    num++;
    // 将数值与状态写回
    this.setData({
      num: num,
      dis_cost: (that.data.roomPriceSum * 1) * (num * 1)
    });
    that.discountShow();
  },
  //减少数量
  reduceNub() {
    let that = this;    
    var num = this.data.num;
    // 如果大于1时，才可以减
    if (num > 1) {
      num--;
    }
    // 将数值与状态写回
    this.setData({
      num: num,
      dis_cost: that.data.roomPriceSum * 1 * (num * 1)
    });
    that.discountShow();
  },
  // 点击去预定按钮
  goReserve (formId) {
    let that = this;
    console.log(that.data.contacts);
    if (that.data.contacts == "") {
      my.alert({
        title: '请填写入住联系人' 
      });
      return false;
    } else if (that.data.contacts.length < 2) {
      my.alert({
        title: '名字太短了，请重新输入'
      });
      return false;
    } else if (that.data.phone == "") {
      my.alert({
        title: '请填写入住手机号码'
      });
      return false;
    } else if (that.data.phone.length != 11) {
      my.alert({
        title: '请输入正确的手机号码'
      });
      return false;
    };
    if (!that.data.clickSign) {
      return false;
    }
    that.setData({
      clickSign: false
    });
    setTimeout(function(){
      that.setData({
        clickSign: true
      });
    }, 3000)
    that.postData(formId);
  },
  // 跳转到时间选择界面
  selectTime () {
    my.navigateTo({
      url: './../time/time-native'
    });
  },
  // 跳转到优惠选择方式
  discount () {
    let that = this;
    my.getNetworkType({
      success: (res) => {
        if (res.networkType) {
          my.navigateTo({
            url: './../order/select-discount-way?price=' + that.data.dis_cost
          });
        } else {
          my.alert({
            content: '网络异常，请检查您的网络' 
          });
        }
      }
    })
  },
  // 设置缓存时间
  setTime () {
    let that = this;
    let inTime = my.getStorageSync({
      key: 'inTime',
    }).data;
    let outTime = my.getStorageSync({
      key: 'outTime',
    }).data;
    let inTimeDay = inTime;
    let lightLong = (new Date(outTime)) - (new Date(inTime));
    try {
      this.setData({
        inTime: my.getStorageSync({
          key: 'inTime',
        }).data.slice(5, 10),
        outTime: my.getStorageSync({
          key: 'outTime',
        }).data.slice(5, 10),
        inTimeDay: inTimeDay,
        lightLong: lightLong / 86400000
      });
    } catch (err) {
      this.setData({
        inTime: '',
        outTime: '',
        inTimeDay: '',
        lightLong: 0
      });
    }
    console.log("一共" + that.data.lightLong + '晚');
  },
  // 获取详情数据
  getData (id) {
    let that = this;
    // 读取缓存酒店详情数据
    utils.getData('SingleRoomDetails', {
      room_id: that.data.room_id,
      start: my.getStorageSync({
        key: 'inTime',
      }).data,
      end: my.getStorageSync({
        key: 'outTime',
      }).data,
      user_type: that.data.menber_type
    }, (res) => {
      that.setData({
        roomInfo: res.data.data,
        bannerImg: res.data.data.img.split(','),
        dis_cost: that.data.roomPriceSum * 1 * (that.data.num * 1)
      });
    }, (err) => {
      console.log(err);
    });
    // 获取酒店数据
    let hotel_info = JSON.parse(my.getStorageSync({
      key: 'hotel_info', // 缓存数据的key
    }).data)
    let breakfast = [
      { name: '0', value: '有' },
      { name: '1', value: '无', checked: true }
    ]; 
    let n_breakfast = [
      { name: '1', value: '无', checked: true }
    ];
    that.setData({
      items: hotel_info.breakfast == 0 ? n_breakfast : breakfast,
      hotel_info: hotel_info
    });
    // 获取活动数据
    utils.getData('SingleSystemDetails', {}, function(res){
      console.log("活动信息");
      console.log(res.data.data)
      my.hideLoading();
      that.setData({
        activity_conetnt: true
      });
      wxParse.wxParse('activity_conetnt', 'html', res.data.data.activity_conetnt ? res.data.data.activity_conetnt : "", that, 5);
    }, function () {
      my.hideLoading();
    })
  },
  // 选择闪住闪退
  authCost () {
    this.setData({
      yj_sign: !this.data.yj_sign
    })
  },
  // 酒店评价
  hotelComment (id) {
    let that = this;
    my.showLoading();
    utils.getData('SingleAssessList', {
      seller_id: base.seller_id,
      page: that.data.page,
      size: that.data.size
    }, (res) => {
      my.hideLoading();
      that.setData({
        commentList: that.data.commentList.concat(res.data.data.list),
        page: that.data.page + 1,
        commentCount: res.data.data.num
      });
      console.log(res.data.data);
    }, (err) => {
      my.hideLoading();
      console.log(err);
    });
  },
  // 设置优惠方式
  discountWay () {
    try {
      var discountWayS = JSON.parse(my.getStorageSync({
        key: 'discount', // 缓存数据的key
      }).data);
    } catch (err) {
      var discountWayS = ''
    };
    if (discountWayS == "") {
      this.setData({
        discountType: '',
        discountPrice: 0,
        name: '',
        needCost: 0
      });
    } else if (discountWayS.equitycard_id) {
      this.setData({
        discountType: 'equity',
        discountPrice: discountWayS.rebate,
        name: discountWayS.name
      });
    } else {
      this.setData({
        discountType: 'discount',
        discountPrice: discountWayS.cost,
        name: discountWayS.name,
        needCost: discountWayS.need_cost
      });
    };
    this.discountShow();
  },
  // 
  discountShow () {
    let that = this;
    if (that.data.needCost && that.data.needCost * 1 > 0) {
      if (that.data.needCost * 1 > that.data.dis_cost) {
        that.setData({
          discountType: '',
          discountPrice: 0,
          name: '',
          needCost: 0
        });
      }
    }
  },
  // 点击闪住闪退详情按钮 
  yjDetail () {
    my.navigateTo({
      url: './../pre-authorization/pre-authorization'
    });
  },
  // 获取房间信息
  getRoomDetail () {
    let that = this;
    utils.getData('SingleGetRoomCost', {
      room_id: that.data.room_id,
      arrival_time: my.getStorageSync({
        key: 'inTime',
      }).data,
      departure_time: my.getStorageSync({
        key: 'outTime', // 缓存数据的key
      }).data,
      user_type: that.data.menber_type
    }, (res) => {
      that.setData({
        roomOrderList: res.data.data.list,
        roomPriceSum: res.data.data.sum,
        dis_cost: res.data.data.sum * that.data.num * 1
      });
      that.discountShow();
    }, (err) => {
      my.showToast({
        type: 'fail',
        content: '网络异常，请稍候再试',
        duration: 3000,
        success: function () {}
      });
    })
  },
  onLoad(query) {
    // 页面加载
    this.setData({
      room_id: query.id,
      menber_type: query.type
    });
    // 清空优惠券缓存
    my.setStorageSync({
      key: 'discount',
      data: '',
    });
    let that = this;
    var uid = my.getStorageSync({
      key: 'uid', // 缓存数据的key
    }).data;
    if (!uid || uid == "") {
      utils.getAuthCode(function(res){
        that.setData({
          contacts: res.data.data.list.user_name,
          phone: res.data.data.phone
        })
      });
      return false;
    };
    var userName = !my.getStorageSync({
      key: 'user_name', // 缓存数据的key
    }).data || my.getStorageSync({
      key: 'user_name', // 缓存数据的key
    }).data == "" || my.getStorageSync({
      key: 'user_name', // 缓存数据的key
    }).data == null ? "" : my.getStorageSync({
      key: 'user_name', // 缓存数据的key
    }).data;
    var userPhone = !my.getStorageSync({
      key: 'phone', // 缓存数据的key
    }).data || my.getStorageSync({
      key: 'phone', // 缓存数据的key
    }).data == "" || my.getStorageSync({
      key: 'phone', // 缓存数据的key
    }).data == null ? "" : my.getStorageSync({
      key: 'phone', // 缓存数据的key
    }).data;
    that.setData({
      contacts: userName,
      phone: userPhone
    })
  },
  detail(e) {
    console.log(e);
  },
  onReady() {
    // 页面加载完成
  },
  onShow() {
    // 页面显示
    this.setTime();
    this.getData();
    this.getRoomDetail();
    this.discountWay();
    this.hotelComment();
  },
  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
    this.hotelComment();
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: my.getStorageSync({
        key: 'hotel_name', // 缓存数据的key
      }).data,
      desc: my.getStorageSync({
        key: 'my_app_description', // 缓存数据的key
      }).data,
      path: 'pages/index/index?share=true',
      success: function (e) {
        console.log(e);
      }
    };
  }
});
